// 全局变量
let isEditing = false;
let editingId = null;

// 页面加载完成后获取学生列表
document.addEventListener('DOMContentLoaded', () => {
    fetchStudents();
});

// 获取学生列表
async function fetchStudents() {
    try {
        const response = await fetch('/api/students');
        const students = await response.json();
        displayStudents(students);
    } catch (error) {
        console.error('获取学生列表失败:', error);
        alert('获取学生列表失败');
    }
}

// 显示学生列表
function displayStudents(students) {
    const tbody = document.getElementById('studentList');
    tbody.innerHTML = '';

    students.forEach(student => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${student.student_id}</td>
            <td>${student.name}</td>
            <td>${student.gender}</td>
            <td>${student.phone}</td>
            <td>${student.room_no}</td>
            <td>
                <button class="action-btn edit-btn" onclick="editStudent(${student.id})">编辑</button>
                <button class="action-btn delete-btn" onclick="deleteStudent(${student.id})">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 显示添加表单
function showAddForm() {
    isEditing = false;
    editingId = null;
    document.getElementById('formTitle').textContent = '添加学生';
    document.getElementById('addEditForm').reset();
    document.getElementById('studentForm').style.display = 'block';
}

// 隐藏表单
function hideForm() {
    document.getElementById('studentForm').style.display = 'none';
    document.getElementById('addEditForm').reset();
}

// 编辑学生信息
async function editStudent(id) {
    try {
        const response = await fetch(`/api/students/${id}`);
        const student = await response.json();
        
        isEditing = true;
        editingId = id;
        document.getElementById('formTitle').textContent = '编辑学生信息';
        
        // 填充表单
        document.getElementById('studentID').value = student.student_id;
        document.getElementById('name').value = student.name;
        document.getElementById('gender').value = student.gender;
        document.getElementById('phone').value = student.phone;
        document.getElementById('roomNo').value = student.room_no;
        
        document.getElementById('studentForm').style.display = 'block';
    } catch (error) {
        console.error('获取学生信息失败:', error);
        alert('获取学生信息失败');
    }
}

// 删除学生
async function deleteStudent(id) {
    if (!confirm('确定要删除这名学生的信息吗？')) {
        return;
    }

    try {
        const response = await fetch(`/api/students/${id}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            fetchStudents(); // 刷新列表
            alert('删除成功');
        } else {
            throw new Error('删除失败');
        }
    } catch (error) {
        console.error('删除学生失败:', error);
        alert('删除学生失败');
    }
}

// 处理表单提交
async function handleSubmit(event) {
    event.preventDefault();

    const studentData = {
        student_id: document.getElementById('studentID').value,
        name: document.getElementById('name').value,
        gender: document.getElementById('gender').value,
        phone: document.getElementById('phone').value,
        room_no: document.getElementById('roomNo').value
    };

    try {
        const url = isEditing ? `/api/students/${editingId}` : '/api/students';
        const method = isEditing ? 'PUT' : 'POST';

        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(studentData)
        });

        if (response.ok) {
            hideForm();
            fetchStudents(); // 刷新列表
            alert(isEditing ? '更新成功' : '添加成功');
        } else {
            throw new Error(isEditing ? '更新失败' : '添加失败');
        }
    } catch (error) {
        console.error('操作失败:', error);
        alert('操作失败');
    }
}